<script setup lang="ts">

import {Plus} from "@element-plus/icons-vue";
import {ref, onBeforeUpdate, onUpdated} from 'vue';
import axios from "axios";

import {ServerHost, loginUser} from "@/main";
import PostOrEditGoods from "@/components/goodsManage/PostOrEditGoods.vue";
import {downloadImg} from "@/utils";

console.log('shop')

// 获取商品列表
const goodsList = ref([])
axios.get(ServerHost + '/getGoodsList')
    .then(res => {
      if (res.status == 200) {
        goodsList.value = res.data
      }
    })

// 懒加载商品图片
const goodsImgItemRefs = ref([]);
const setGoodsImgRef = (el: any) => {
  if (el) {
    goodsImgItemRefs.value.push(el);
  }
}

onBeforeUpdate(() => {
  goodsImgItemRefs.value = [];
});

const goodHasLoadImgIdList = ref([]); // 已经加载过图片的商品id列表
// 监听商品图片元素是否进入可视区域，如果进入则加载图片
onUpdated(() => {
  goodsImgItemRefs.value.forEach((item: any) => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const goodId = item.getAttribute('data-id');
          if (!goodHasLoadImgIdList.value.includes(goodId)) {
            goodHasLoadImgIdList.value.push(goodId);
            const goods = goodsList.value.find(goods => goods.id == goodId)
            //   加载图片
            downloadImg(goods.img, "goodsImg/")
                .then(res => {
                  if (res.status === 200) {
                    // 获取图片类型
                    const type = goods.img.split('.')[1]
                    let mime: string
                    if ((['jpg', 'jpeg'] as any).includes('jpg'))
                      mime = 'image/jpeg'
                    else
                      mime = `image/${type}`
                    const blob = new Blob([res.data], {type: mime})
                    const imgFile = new File([blob], goods.img, {type: mime})
                    goods.imgUrl = URL.createObjectURL(imgFile)
                    console.log(goods)
                  }
                })
          }

        }
      });
    });
    observer.observe(item);
  });
});

const postOrEditGoodsDialogVisible = ref(false)

const onAddGoods = () => {
  console.log("添加商品")
  postOrEditGoodsDialogVisible.value = true
}
</script>

<template>
  <!-- 固定在右下角的上架农产品按钮 -->
  <el-tooltip
      v-if="loginUser != null && (loginUser.username === 'rrsRoot' || loginUser.isSeller)"
      class="add-goods-tooltip"
      content="上架农产品"
      placement="top">
    <el-button class="add-agritainment-bt" circle @click="onAddGoods">
      <template #icon>
        <el-icon :size="20">
          <Plus/>
        </el-icon>
      </template>
    </el-button>
  </el-tooltip>

  <!-- 添加农产品 Dialog-->
  <el-dialog
      v-model="postOrEditGoodsDialogVisible"
      title="添加农产品">
    <PostOrEditGoods type="new"/>
  </el-dialog>

  <!-- 商品列表 -->
  <div class="goods-list p-4 m-auto">
    <div v-for="goods in goodsList" :ref="setGoodsImgRef" :data-id="goods.id">
      <el-card class="goods-item">
        <router-link :to="'/goods/' + goods.id" target="_blank">
          <div class="goods-item-img-div mb-1">
            <img class="good-item-img" :src="goods.imgUrl" alt="Goods Img"/>
          </div>
          <p class="goods-item-name">{{ goods.name }}</p>
          <div class="flex items-center justify-between">
            <p class="goods-item-price"><span class="goods-item-price-sign">￥</span>{{ (goods.priceCent / 100).toFixed(2) }}</p>
            <el-tag>已售{{ goods.sales }}</el-tag>
          </div>
        </router-link>
      </el-card>
    </div>
  </div>

</template>

<style scoped lang="scss">
.add-agritainment-bt {
  width: 60px;
  height: 60px;
  position: fixed;
  right: 80px;
  bottom: 80px;
}

.goods-list {
  width: fit-content;
  display: grid;
  grid-template-columns: repeat(5, 300px);
  grid-gap: 10px;
  //grid-area: center;
  //place-self: center;
}

.goods-item {
  width: 300px;
  height: auto;
}

.goods-item-img-div {
  aspect-ratio: 1;
}

.good-item-img {
  width: 100%;
  height: 100%;
  border-radius: 2px;
  object-fit: cover;
}

.goods-item-name {
  font-size: 1.2rem;
}

.goods-item-price-sign {
  font-size: 0.8rem;
}

.goods-item-price {
  font-family: "思源宋体 Heavy", serif;
  font-size: 1.2rem;
  color: var(--el-color-primary);

}
</style>
